﻿using FairyGUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class EquipInfoPanel : BasePopupPanel
{
    private Equip equip;
    private bool isChangeEquip;
    /// <summary>
    /// 更换
    /// </summary>
    private GButton btnChange;
    /// <summary>
    /// 卸下
    /// </summary>
    private GButton btnDown;
    /// <summary>
    /// 强化
    /// </summary>
    private GButton btnQiangHua;
    /// <summary>
    /// 精炼
    /// </summary>
    private GButton btnJingLian;
    /// <summary>
    /// 灵石升级
    /// </summary>
    private GButton btnLingShi;
    /// <summary>
    /// 注灵
    /// </summary>
    private GButton btnZhuLin;
    /// <summary>
    /// 强化动画
    /// </summary>
    private Transition transQiangHua;
    /// <summary>
    /// 装备名称
    /// </summary>
    private GTextField tfTitle;
    /// <summary>
    /// 装备信息
    /// </summary>
    private GTextField tfInfo;
    /// <summary>
    /// 精炼加成
    /// </summary>
    private GList lsJingLianUp;
    /// <summary>
    /// 强化值显示
    /// </summary>
    private GTextField tfQiangHuaUp;
    /// <summary>
    /// 强化消耗显示
    /// </summary>
    private GTextField tfQiangHuaUp1;
    /// <summary>
    /// 精炼值显示
    /// </summary>
    private GTextField tfJingLianUp;
    /// <summary>
    /// 精炼消耗显示
    /// </summary>
    private GTextField tfJingLianUp1;
    /// <summary>
    /// 灵石列表
    /// </summary>
    private GList listLingShi;
    /// <summary>
    /// 精炼道具
    /// </summary>
    private GRichTextField tfJianLianItem;
    /// <summary>
    /// 灵石道具
    /// </summary>
    private GRichTextField tfLingShiItem;
    /// <summary>
    /// 注灵
    /// </summary>
    private GRichTextField tfZhuLingItem;
    /// <summary>
    /// 
    /// </summary>
    private GTextField tfJianLianItemCount;

    private GTextField[] tfTotalAttribute;

    public override void Init()
    {
        base.Init();

        frame = view.GetChild("frame").asCom;
        closeTransition = view.GetTransition("t1");

        btnChange = frame.GetChild("n32").asButton;
        btnDown = frame.GetChild("n33").asButton;
        btnQiangHua = frame.GetChild("n31").asButton;
        transQiangHua = btnQiangHua.GetTransition("t0");
        btnJingLian = frame.GetChild("n34").asButton;
        btnLingShi = frame.GetChild("n35").asButton;
        btnZhuLin = frame.GetChild("n36").asButton;
        tfTitle = frame.GetChild("title").asTextField;
        tfInfo = frame.GetChild("n4").asTextField;
        lsJingLianUp = frame.GetChild("n30").asList;
        tfQiangHuaUp = frame.GetChild("n9").asTextField;
        tfQiangHuaUp1 = frame.GetChild("n12").asTextField;
        tfJingLianUp = frame.GetChild("n10").asTextField;
        tfJingLianUp1 = frame.GetChild("n14").asTextField;
        listLingShi = frame.GetChild("n17").asList;
        tfJianLianItem = frame.GetChild("n15").asRichTextField;
        tfJianLianItemCount = frame.GetChild("n16").asTextField;
        tfLingShiItem = frame.GetChild("n19").asRichTextField;
        tfZhuLingItem = frame.GetChild("n27").asRichTextField;
        tfTotalAttribute = new GTextField[5];
        tfTotalAttribute[0] = frame.GetChild("n7").asTextField;
        tfTotalAttribute[1] = frame.GetChild("n8").asTextField;
        tfTotalAttribute[2] = frame.GetChild("n37").asTextField;
        tfTotalAttribute[3] = frame.GetChild("n38").asTextField;
        tfTotalAttribute[4] = frame.GetChild("n39").asTextField;

        btnChange.onClick.Add(OnChangeClick);
        btnDown.onClick.Add(OnDownClick);
        btnQiangHua.onClick.Add(OnQiangHua);
        btnJingLian.onClick.Add(OnJingLian);
        btnLingShi.onClick.Add(OnLingShi);
        btnZhuLin.onClick.Add(OnZhuLin);
        listLingShi.onClickItem.Add(OnLingShiClick);
        tfJianLianItem.onClick.Add(OnJianLianItemClick);
        tfLingShiItem.onClick.Add(OnLingShiItemClick);
        tfZhuLingItem.onClick.Add(OnZhuLingItemClick);

        List<EquipJianLianUp> roleUps = EquipJianLianUpMgr.Dict.Values.ToList();
        for (int i=0; i<roleUps.Count; i++)
        {
            GTextField gText = UIPackage.CreateObject("Main", "text_jinglianadd").asCom.GetChild("n0").asTextField;
            lsJingLianUp.AddChild(gText);
        }
    }

    public override void Show(params object[] para)
    {
        MsgListenerMgr.AddMsgListener(MsgListenerType.EquipPosChange, OnEquipPosChangeMsg);
        MsgListenerMgr.AddMsgListener(MsgListenerType.EquipAttributeChange, OnEquipAttributeChange);

        equip = para[0] as Equip;
        if (equip.szPos > 0)
        {
            btnChange.visible = true;
            btnDown.visible = true;
            btnQiangHua.visible = true;
            btnLingShi.visible = true;
            btnZhuLin.visible = true;
            btnJingLian.visible = true;
        }
        else
        {
            btnChange.visible = false;
            btnDown.visible = false;
            btnQiangHua.visible = false;
            btnLingShi.visible = false;
            btnZhuLin.visible = false;
            btnJingLian.visible = false;
        }


        isChangeEquip = false;
        SetInfo();
        listLingShi.selectedIndex = 0;
        listLingShi.onClickItem.Call();

        base.Show();
    }

    public override void Close()
    {
        MsgListenerMgr.RemoveMsgListener(MsgListenerType.EquipPosChange, OnEquipPosChangeMsg);
        MsgListenerMgr.RemoveMsgListener(MsgListenerType.EquipAttributeChange, OnEquipAttributeChange);

        if (isChangeEquip)
        {
            if (equip != null && equip.InitEquip != null)
            {
                int equipType = equip.InitEquip.kind;
                CommonUtil.ChangeEquip(equip.szPos, equipType);
            }
            isChangeEquip = false;
        }
        equip = null;
        base.Close();
    }


    protected override GComponent CreateView()
    {
        return UIPackage.CreateObject("Main", "panel_equipinfo1").asCom;
    }

    private void OnChangeClick(EventContext context)
    {
        isChangeEquip = true;
        Close();
    }

    private void OnDownClick(EventContext context)
    {
        if (equip == null)
        {
            return;
        }

        RequestHelper.SendDownEquipRequest(equip);
    }

    private void SetInfo()
    {
        if (equip == null)
        {
            return;
        }

        InitEquip initEquip = equip.InitEquip;
        if (initEquip == null)
        {
            return;
        }

        tfTitle.text = string.Format("{0}(强化{1}级)(精炼{2}级)(灵石{3}级)(注灵{4}级)",
            initEquip.name, equip.QiangHuaLevel, equip.JingLianLevel, equip.GetTotalLingShiLevel(), equip.ZhuLingLevel);
        tfTitle.color = CommonUtil.GetEquipColor(initEquip.quality);
        tfInfo.text = initEquip.info;

        string posName = CommonUtil.GetEquipPosName(initEquip.kind);

        //总属性
        SetTotalAttribute();

        //精炼加成
        SetJianLianJiaChen(initEquip, posName);

        //强化
        SetQiangHua(initEquip, posName);

        //精炼
        SetJianLian(initEquip, posName);

        //灵石
        SetLingShi();

        //注灵
        SetZhuLing(initEquip);
    }

    /// <summary>
    /// 总属性
    /// </summary>
    private void SetTotalAttribute()
    {
        for (int i=0; i< tfTotalAttribute.Length; i++)
        {
            tfTotalAttribute[i].visible = false;
        }
        int idx = 0;
        Dictionary<AttributeType, int> atts = equip.Attribute.Atts;
        foreach (var item in atts)
        {
            if (item.Value > 0)
            {
                tfTotalAttribute[idx].visible = true;
                if (item.Key == AttributeType.DEX || item.Key == AttributeType.CRT || item.Key == AttributeType.EVD || item.Key == AttributeType.KBL)
                {
                    float value = item.Value;
                    tfTotalAttribute[idx].text = string.Format("{0}+{1}%", Attribute.Names[(int)item.Key], CommonUtil.GetRate(value));
                    tfTotalAttribute[idx].color = CommonUtil.Orange;
                }
                else
                {
                    tfTotalAttribute[idx].text = string.Format("{0}+{1}", Attribute.Names[(int)item.Key], CommonUtil.NumberToString(item.Value));
                    tfTotalAttribute[idx].color = CommonUtil.White;
                }
                idx++;
            }
        }
    }

    /// <summary>
    /// 设置注灵
    /// </summary>
    private void SetZhuLing(InitEquip initEquip)
    {
        string name1 = "";
        string name2 = "";

        int currValue1 = 0;
        float currValue2 = 0;

        int nextValue1 = 0;
        float nextValue2 = 0;

        int count = 0;
        int itemId = 0;
        if (initEquip.kind == 1)
        {
            name1 = "攻击";
            name2 = "抗暴";
            if (ZhuLingWeaponMgr.Dict.TryGetValue(equip.ZhuLingLevel, out ZhuLingWeapon zhuLing1))
            {
                currValue1 = zhuLing1.atk;
                currValue2 = zhuLing1.kbl;
            }
            if (ZhuLingWeaponMgr.Dict.TryGetValue(equip.ZhuLingLevel+1, out ZhuLingWeapon zhuLing2))
            {
                nextValue1 = zhuLing2.atk;
                nextValue2 = zhuLing2.kbl;
                itemId = zhuLing2.use_item_id;
                count = zhuLing2.use_item_count;
            }
        }
        else if (initEquip.kind == 2)
        {
            name1 = "物防";
            name2 = "闪避";
            if (ZhuLingClothesMgr.Dict.TryGetValue(equip.ZhuLingLevel, out ZhuLingClothes zhuLing1))
            {
                currValue1 = zhuLing1.def;
                currValue2 = zhuLing1.evd;
            }
            if (ZhuLingClothesMgr.Dict.TryGetValue(equip.ZhuLingLevel + 1, out ZhuLingClothes zhuLing2))
            {
                nextValue1 = zhuLing2.def;
                nextValue2 = zhuLing2.evd;
                itemId = zhuLing2.use_item_id;
                count = zhuLing2.use_item_count;
            }
        }
        else if (initEquip.kind == 3)
        {
            name1 = "生命";
            name2 = "命中";
            if (ZhuLingRingMgr.Dict.TryGetValue(equip.ZhuLingLevel, out ZhuLingRing zhuLing1))
            {
                currValue1 = zhuLing1.hp;
                currValue2 = zhuLing1.dex;
            }
            if (ZhuLingRingMgr.Dict.TryGetValue(equip.ZhuLingLevel + 1, out ZhuLingRing zhuLing2))
            {
                nextValue1 = zhuLing2.hp;
                nextValue2 = zhuLing2.dex;
                itemId = zhuLing2.use_item_id;
                count = zhuLing2.use_item_count;
            }
        }
        else
        {
            name1 = "法防";
            name2 = "暴击";
            if (ZhuLingShoeMgr.Dict.TryGetValue(equip.ZhuLingLevel, out ZhuLingShoe zhuLing1))
            {
                currValue1 = zhuLing1.rgs;
                currValue2 = zhuLing1.crt;
            }
            if (ZhuLingShoeMgr.Dict.TryGetValue(equip.ZhuLingLevel + 1, out ZhuLingShoe zhuLing2))
            {
                nextValue1 = zhuLing2.rgs;
                nextValue2 = zhuLing2.crt;
                itemId = zhuLing2.use_item_id;
                count = zhuLing2.use_item_count;
            }
        }
        tfZhuLingItem.data = itemId;

        GTextField tfCurr1 = frame.GetChild("n22").asTextField;
        GTextField tfCurr2 = frame.GetChild("n23").asTextField;

        tfCurr1.text = string.Format("{0}+{1}", name1, CommonUtil.NumberToString(currValue1));
        tfCurr2.text = string.Format("{0}+{1}%",name2, CommonUtil.GetRate(currValue2));


        GTextField tfNext1 = frame.GetChild("n24").asTextField;
        GTextField tfNext2 = frame.GetChild("n25").asTextField;

        tfNext1.text = string.Format("{0}+{1}", name1, CommonUtil.NumberToString(nextValue1));
        tfNext2.text = string.Format("{0}+{1}%", name2, CommonUtil.GetRate(nextValue2));

        int totalCount = GameNetwork.Player.PackItemMgr.GetCount(itemId);
        GTextField tfCount = frame.GetChild("n28").asTextField;
        tfCount.text = string.Format("{0}/{1}", CommonUtil.NumberToString(count), CommonUtil.NumberToString(totalCount));
        tfCount.color = count > totalCount ? CommonUtil.Red : CommonUtil.White;
    }

    /// <summary>
    /// 设置灵石信息
    /// </summary>
    private void SetLingShi()
    {
        GObject[] lingshis = listLingShi.GetChildren();
        for (int i = 0; i < lingshis.Length; i++)
        {
            GButton btnLingShi = lingshis[i].asButton;
            if (btnLingShi == null)
            {
                continue;
            }
            GTextField tfLv = btnLingShi.GetChild("n3").asTextField;
            tfLv.text = string.Format("({0}级)", equip.LingShiLevel[i]);
        }
    }

    /// <summary>
    /// 精炼信息
    /// </summary>
    private void SetJianLian(InitEquip initEquip, string posName)
    {
        int currValue = 0, nextValue = 0;
        long xiaoHao = 0;
        if (EquipJianLianMgr.Dict.TryGetValue(equip.JingLianLevel, out EquipJianLian equipJianLian1))
        {
            currValue = equipJianLian1.GetValue(initEquip.kind);
        }
        if (EquipJianLianMgr.Dict.TryGetValue(equip.JingLianLevel + 1, out EquipJianLian equipJianLian2))
        {
            nextValue = equipJianLian2.GetValue(initEquip.kind);
            xiaoHao = equipJianLian2.use_gold;
            if (InitItemMgr.Dict.TryGetValue(equipJianLian2.use_item_id, out InitItem initItem))
            {
                tfJianLianItem.text = string.Format("{0}:", initItem.name);
                tfJianLianItem.data = initItem.id;
                tfJianLianItemCount.text = string.Format("{0}/{1}", equipJianLian2.use_item_count, GameNetwork.Player.PackItemMgr.GetCount(equipJianLian2.use_item_id));
            }
        }
        tfJingLianUp.text = string.Format("精炼(当前:{0}+{1} 下级:{0}+{2})", posName, CommonUtil.NumberToString(currValue), CommonUtil.NumberToString(nextValue));
        tfJingLianUp1.text = string.Format("{0}/{1}", CommonUtil.NumberToString(xiaoHao), CommonUtil.NumberToString(GameNetwork.Player.BaseInfo.Gold));
        tfJingLianUp1.color = xiaoHao > GameNetwork.Player.BaseInfo.Gold ? CommonUtil.Red : CommonUtil.White;
    }

    /// <summary>
    /// 强化信息
    /// </summary>
    private void SetQiangHua(InitEquip initEquip, string posName)
    {
        int currValue = 0;
        int nextValue = 0;
        long xiaoHao = 0;
        if (EquipQiangHuaMgr.Dict.TryGetValue(equip.QiangHuaLevel, out EquipQiangHua equipQiangHua1))
        {
            currValue = equipQiangHua1.GetValue(initEquip.kind);
        }

        if (EquipQiangHuaMgr.Dict.TryGetValue(equip.QiangHuaLevel + 1, out EquipQiangHua equipQiangHua2))
        {
            nextValue = equipQiangHua2.GetValue(initEquip.kind);
            xiaoHao = equipQiangHua2.use_gold;
        }

        tfQiangHuaUp.text = string.Format("强化(当前:{0}+{1} 下级:{0}+{2})", posName, CommonUtil.NumberToString(currValue), CommonUtil.NumberToString(nextValue));
        tfQiangHuaUp1.text = string.Format("{0}/{1}", CommonUtil.NumberToString(xiaoHao), CommonUtil.NumberToString(GameNetwork.Player.BaseInfo.Gold));
        tfQiangHuaUp1.color = xiaoHao > GameNetwork.Player.BaseInfo.Gold ? CommonUtil.Red : CommonUtil.White;
    }

    /// <summary>
    /// 精炼加成
    /// </summary>
    private void SetJianLianJiaChen(InitEquip initEquip, string posName)
    {
        int idx = -1;
        GObject[] gObjects = lsJingLianUp.GetChildren();
        List<EquipJianLianUp> ups = EquipJianLianUpMgr.Dict.Values.ToList();
        for (int i = 0; i < gObjects.Length; i++)
        {
            GTextField gText = gObjects[i].asTextField;

            gText.text = string.Format("{0}+{1}(装备精炼{2}级激活)", posName, ups[i].GetValue(initEquip.kind), ups[i].level);
            if (equip.JingLianLevel >= ups[i].level)
            {
                gText.color = CommonUtil.Green;
                idx = i;
            }
            else
            {
                gText.color = CommonUtil.White;
            }
        }

        if (idx != -1)
        {
            lsJingLianUp.ScrollToView(idx);
        }
    }

    private void OnLingShiClick(EventContext context)
    {
        if (listLingShi.selectedIndex < 0 || equip == null)
        {
            return;
        }

        string[] names = new string[] { "攻击", "物防", "法防", "生命" };

        int lingshiLev = equip.LingShiLevel[listLingShi.selectedIndex];
        int currValue = 0;
        int nextValue = 0;
        if (EquipLingShiMgr.Dict.TryGetValue(lingshiLev, out EquipLingShi equipLingShi1))
        {
            equipLingShi1.GetInfo(listLingShi.selectedIndex, out currValue, out _, out _);
        }

        if (EquipLingShiMgr.Dict.TryGetValue(lingshiLev+1, out EquipLingShi equipLingShi2))
        {
            int itemId;
            int count;
            equipLingShi2.GetInfo(listLingShi.selectedIndex, out nextValue, out itemId, out count);
            if (InitItemMgr.Dict.TryGetValue(itemId, out InitItem initItem))
            {
                tfLingShiItem.data = itemId;
                tfLingShiItem.text = string.Format("{0}:", initItem.name);

                int totalCount = GameNetwork.Player.PackItemMgr.GetCount(itemId);
                GTextField tfCount = frame.GetChild("n20").asTextField;
                tfCount.text = string.Format("{0}/{1}", CommonUtil.NumberToString(count), CommonUtil.NumberToString(totalCount));
                tfCount.color = count > totalCount ? CommonUtil.Red : CommonUtil.White;
            }
        }

        GTextField tfValue = frame.GetChild("n18").asTextField;
        tfValue.text = string.Format("灵石(当前:{0}+{1}下级:{0}+{2})", names[listLingShi.selectedIndex], CommonUtil.NumberToString(currValue), CommonUtil.NumberToString(nextValue));
    }

    private void OnJianLianItemClick(EventContext context)
    {
        if (tfJianLianItem.data == null)
        {
            return;
        }

        long itemId = (long)tfJianLianItem.data;
        if (InitItemMgr.Dict.TryGetValue(itemId, out InitItem initItem))
        {
            PopupPanelManager.Open<ItemTipPanel>(initItem);
        }
    }

    private void OnZhuLingItemClick(EventContext context)
    {
        if (tfZhuLingItem.data == null)
        {
            return;
        }

        int itemId = (int)tfZhuLingItem.data;
        if (InitItemMgr.Dict.TryGetValue(itemId, out InitItem initItem))
        {
            PopupPanelManager.Open<ItemTipPanel>(initItem);
        }
    }

    private void OnLingShiItemClick(EventContext context)
    {
        if (tfLingShiItem.data == null)
        {
            return;
        }

        long itemId = (int)tfLingShiItem.data;
        if (InitItemMgr.Dict.TryGetValue(itemId, out InitItem initItem))
        {
            PopupPanelManager.Open<ItemTipPanel>(initItem);
        }
    }

    private void OnZhuLin(EventContext context)
    {
        if (equip == null || equip.InitEquip == null)
        {
            return;
        }

        int itemId;
        int itemCount;
        if (equip.InitEquip.kind == 1)
        {
            if (!ZhuLingRingMgr.Dict.TryGetValue(equip.ZhuLingLevel + 1, out ZhuLingRing zhuling))
            {
                FlyTextPanelMgr.Show("注灵等级已达到最大等级");
                return;
            }
            itemId = zhuling.use_item_id;
            itemCount = zhuling.use_item_count;
        }
        else if (equip.InitEquip.kind == 2)
        {
            if (!ZhuLingClothesMgr.Dict.TryGetValue(equip.ZhuLingLevel + 1, out ZhuLingClothes zhuling))
            {
                FlyTextPanelMgr.Show("注灵等级已达到最大等级");
                return;
            }

            itemId = zhuling.use_item_id;
            itemCount = zhuling.use_item_count;
        }
        else if (equip.InitEquip.kind == 3)
        {
            if (!ZhuLingRingMgr.Dict.TryGetValue(equip.ZhuLingLevel + 1, out ZhuLingRing zhuling))
            {
                FlyTextPanelMgr.Show("注灵等级已达到最大等级");
                return;
            }

            itemId = zhuling.use_item_id;
            itemCount = zhuling.use_item_count;
        }
        else
        {
            if (!ZhuLingShoeMgr.Dict.TryGetValue(equip.ZhuLingLevel + 1, out ZhuLingShoe zhuling))
            {
                FlyTextPanelMgr.Show("注灵等级已达到最大等级");
                return;
            }

            itemId = zhuling.use_item_id;
            itemCount = zhuling.use_item_count;
        }

        if (itemId > 0)
        {
            if (!GameNetwork.Player.PackItemMgr.TryGetBySId(itemId, out Item item) || item.Count < itemCount)
            {
                FlyTextPanelMgr.Show("注灵道具数量不足");
                return;
            }
        }

        RequestHelper.SendZhuLingEquipRequest(equip.id);
    }

    private void OnLingShi(EventContext context)
    {
        if (listLingShi.selectedIndex < 0 || equip == null)
        {
            return;
        }

        int lingshiLev = equip.LingShiLevel[listLingShi.selectedIndex];

        if (!EquipLingShiMgr.Dict.TryGetValue(lingshiLev + 1, out EquipLingShi equipLingShi2))
        {
            FlyTextPanelMgr.Show("灵石等级已达到最大等级");
            return;
        }

        equipLingShi2.GetInfo(listLingShi.selectedIndex, out _, out int itemId, out int count);

        if (!GameNetwork.Player.PackItemMgr.TryGetBySId(itemId, out Item item) || item.Count < count)
        {
            FlyTextPanelMgr.Show("灵石道具数量不足");
            return;
        }

        RequestHelper.SendLingShiQiangHuaRequest(equip.id, (byte)listLingShi.selectedIndex);
    }

    private void OnJingLian(EventContext context)
    {
        if (equip == null)
        {
            return;
        }

        if (!EquipJianLianMgr.Dict.TryGetValue(equip.JingLianLevel + 1, out EquipJianLian equipJianLian))
        {
            FlyTextPanelMgr.Show("精炼等级已达到最大等级");
            return;
        }

        if (equipJianLian.use_gold > GameNetwork.Player.BaseInfo.Gold)
        {
            FlyTextPanelMgr.Show("金币不足");
            return;
        }

        if (!GameNetwork.Player.PackItemMgr.TryGetBySId(equipJianLian.use_item_id, out Item item) || item.Count < equipJianLian.use_item_count)
        {
            FlyTextPanelMgr.Show("精炼道具数量不足");
            return;
        }

        RequestHelper.SendJingLianEquipRequest(equip.id);
    }

    private void OnQiangHua(EventContext context)
    {
        if (equip == null)
        {
            return;
        }

        if (!EquipQiangHuaMgr.Dict.TryGetValue(equip.QiangHuaLevel + 1, out EquipQiangHua qiangHua))
        {
            FlyTextPanelMgr.Show("强化已达到最大等级");
            return;
        }

        if (qiangHua.use_gold > GameNetwork.Player.BaseInfo.Gold)
        {
            FlyTextPanelMgr.Show("金币不足");
            return;
        }
        RequestHelper.SendQiangHuaEquipRequest(equip.id);
    }


    private void OnEquipPosChangeMsg(params object[] para)
    {
        Close();
    }

    private void OnEquipAttributeChange(object[] para)
    {
        SetInfo();
        listLingShi.onClickItem.Call();
    }
}
